package com.test.servlet;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.test.database.DBManager;

public class MessageCompose extends HttpServlet {
	private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    		throws ServletException, IOException {
    	response.setContentType("text/html; charset=UTF-8" );
		DataOutputStream dos = new DataOutputStream(response.getOutputStream());
		String username = request.getParameter("username");
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		username = convert(username);
		title = convert(title);
		content = convert(content);
		long msg_id = System.currentTimeMillis();
		String sql = "insert into " + DBManager.TABLE_NAME_MESSAGE + " values ( "
				+ msg_id + ", " + "'" + username + "', "
				+ "'" + title + "', " + "'" + content + "', "
				+ "now()" + ")";
		System.out.println(sql);
		DBManager db = new DBManager();
		int sqlResult = db.update(sql);
		HashMap<String, Object> result = new HashMap<String, Object>();
		result.put("result_code", sqlResult);
		String jsonStr = (new Gson()).toJson(result);
		dos.writeUTF(jsonStr);
		dos.flush();
		dos.close();
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    		throws ServletException, IOException {
    	doGet(request, response);
    }
    
    private String convert(String str) {
		String newStr = null;
		try {
			newStr = new String(str.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return str;
		}
		return newStr;
	}
}
